/* *
 * @Author: chenqinglong
 * @Description: 此js中放公共的方法，大家有用到的统一调用，方法注意写好注释
 * @Date: 2018/5/24 10:05
 * @Param:
 * @return:
 */

/**
 * 初始化多选下拉框
 * @Author:  zhangwei
 * @Date: 2019/3/6 15:05
 * @param id            下拉框的combox id属性
 * @param typeClassCode 下拉框的uce字典数组code
 * @param checkName     下拉选项前的checkbox勾选框的name属性，用于重置清空
 */
function uceDictMultipleCombobox(id,typeClassCode,checkName,params){
    $('#'+id).combobox({
        editable:false,
        valueField:'typeCode',
        textField:'typeName',
        multiple:true,
        loadFilter :  params && params.loadFilter ? params.loadFilter : undefined,
        data:DictDatas[typeClassCode].slice(0),
        formatter:function(row){
            var opts=$(this).combobox('options');
            return '<input type="checkbox" name=checkName class="combobox-checkbox">' + row[opts.textField]+'</input>';
        },
        onLoadSuccess:function(){
            var opts = $(this).combobox('options');
            var target = this;
            var values = $(target).combobox('getValues');//获取选中的值的values
            $.map(values, function (value) {
                var el = opts.finder.getEl(target, value);
                el.find('input.combobox-checkbox')._propAttr('checked', true);
            })
        },
        onSelect: function (row) { //选中一个选项时调用
            var opts = $(this).combobox('options');
            //获取选中的值的values
            var name=$("#"+id).val($(this).combobox('getValues'));
            //设置选中值所对应的复选框为选中状态
            var el = opts.finder.getEl(this, row[opts.valueField]);
            el.find('input.combobox-checkbox')._propAttr('checked', true);
        },
        onUnselect: function (row) {//不选中一个选项时调用
            var opts = $(this).combobox('options');
            //获取选中的值的values
            $("#"+id).val($(this).combobox('getValues'));
            var el = opts.finder.getEl(this, row[opts.valueField]);
            el.find('input.combobox-checkbox')._propAttr('checked', false);
        }
    });
}

/*
** @Author: chutianhua
 * @Description: 工单类型二级联动
 * @Date: 2018/5/24 10:05
 * @Param:CsSmOrderTypeParentComboboxId 父类型元件id,CsSmOrderTypeChildComboboxId 子类型元件id,params参数
 * @return:
*/

var parentId = 0;
var childValue= '';
function setCsSmOrderTypeSelect(csSmOrderTypeParentComboboxId,csSmOrderTypeChildComboboxId,params){
    if(!csSmOrderTypeParentComboboxId){
        console.error("CsSmOrderTypeParentComboboxId不能为空");
        return;
    }

    $('#'+csSmOrderTypeParentComboboxId).uceCombobox({
        width : params && !isNaN(params.width) ? params.width : undefined,
        height : params && !isNaN(params.height) ? params.height : undefined,
        panelWidth : params && !isNaN(params.panelWidth) ? params.panelWidth : undefined,
        panelHeight : params && !isNaN(params.panelHeight) ? params.panelHeight : undefined,
        valueField : params && params.valueField ? params.valueField :'idStr',
        textField : params && params.textField ? params.textField :'name',
        filterFields:params && params.filterFields ? params.filterFields : ["idStr","name"],
        url : params && params.url ? params.url : G_CTX_PATH+'/cs/CsSmOrderType/getCsSmOrderTypeList.do',
        method: params && params.method ? params.method : 'post',
        editable : params && params.editable == true ? true : false,
        onBeforeLoad:function(param){
            param.type=1;
            if(params && params.data && !isEmptyObject(params.data)){
                for (var key in params.data) {
                    param[key]=params.data[key];
                }
            }

        },
        onSelect:function(param){
            //获取父类工单类型的id
            parentId = param.idStr;
            childValue = '';

            $('#' + csSmOrderTypeChildComboboxId).combobox('clear');
            $('#' + csSmOrderTypeChildComboboxId).combobox('reload');

            if(params && params.parentUserMethod){
                params.parentUserMethod(param);
            }
            //2018-07-28
            if(!(params.orderTypeValue && params.orderTypeValue==param.idStr)){
                params.orderChildTypeValue="";
            }

            if( typeof params.onSelect == "function"){
                params.onSelect(param);
            }

        },
        onLoadSuccess:function (data) {
            console.log(data);
            //2018-07-28
            if(params.orderTypeValue){
                $('#' + csSmOrderTypeParentComboboxId).combobox('setValue', params.orderTypeValue);
            }
        }
    });

    $('#'+csSmOrderTypeChildComboboxId).uceCombobox({
        valueField : params && params.valueField ? params.valueField : 'idStr',
        textField : params && params.textField ? params.textField : 'name',
        url : params && params.url ? params.url :G_CTX_PATH+'/cs/CsSmOrderType/getCsSmOrderTypeList.do',
        method: params && params.method ? params.method : 'post',
        editable : params && params.editable == true ? true : false,
        onBeforeLoad:function(param){
            param.type=2;
            param.parentId = parentId;
        },
        onSelect: function(param){
            if(params && params.childUserMethod){
                params.childUserMethod(param,params);
            }
        },
        onLoadSuccess:function () {
            if(childValue != ''){
                $('#' + csSmOrderTypeChildComboboxId).combobox('setValue', childValue);
            }
            //2018-07-28
            if(params.orderChildTypeValue){
                $('#' + csSmOrderTypeChildComboboxId).combobox('setValue', params.orderChildTypeValue);
            }
        }
    });
}

/*
** @Author: Sunny
 * @Description: 工单类型二级联动
 * @Date: 2019/8/16 17:15
 * @Param:CsSmOrderTypeParentComboboxId 父类型元件id,CsSmOrderTypeChildComboboxId 子类型元件id,params参数
 * @return:
*/
var selectFalg = false;
function setCsSmOrderTypeComboxGridSelect(domId,csSmOrderTypeChildComboboxId,params) {
    console.log('加载机构下拉框');
    if (!domId) {
        console.error("domId不能为空！");
        return;
    }
    if (params && params.pageSize != null && params.pageSize != undefined) {
        if (!isNaN(params.pageSize)) {
            params.pageList = [ params.pageSize, params.pageSize * 2,
                params.pageSize * 3, params.pageSize * 4,
                params.pageSize * 5, params.pageSize * 10 ]
            params.pagination = true;
        } else {
            console.error("pageSize必须要为数字！");
            return;
        }
    }
    $("#" + domId)
        .uceCombogrid(
            {
                url : params && params.url ? params.url
                    : G_CTX_PATH+'/cs/CsSmOrderType/getCsSmOrderTypeList.do',
                queryParams : params && params.queryParams ? params.queryParams
                    : undefined,
                filterFields: params && params.filterFields ? params.filterFields
                    : undefined,
                columns : params && params.columns ? params.columns
                    : [ [ {
                        field : 'idStr',
                        hidden : true
                    }, {
                        field : 'typeCode',
                        title : '编码',
                        align : 'left',
                        width : 100
                    }, {
                        field : 'name',
                        title : '名称',
                        align : 'left',
                        width : 250
                    } ] ],
                pagination : params && params.pagination == false ? false
                    : true,
                pageNumber : 1,
                pageSize : params && params.pageSize
                && !isNaN(params.pageSize) ? params.pageSize
                    : undefined,
                pageList : params && params.pageList ? params.pageList
                    : undefined,
                idField : params && params.idField ? params.idField
                    : 'idStr',
                textField : params && params.textField ? params.textField
                    : 'name',
                mode : params && params.mode == 'local' ? 'local'
                    : 'remote',
                loadMsg : '数据加载中请稍后……',
                panelWidth : params && params.panelWidth
                && !isNaN(params.panelWidth) ? params.panelWidth
                    : 350,
                panelHeight : params && params.panelHeight
                && !isNaN(params.panelHeight) ? params.panelHeight
                    : 320,
                singleSelect : params && params.singleSelect == true ? true
                    : false,
                fitColumns : true,
                onSelect : params && params.onSelect ? params.onSelect
                    : function(param){
                        debugger;
                        var row = $(this).datagrid('getSelected');
                        //获取父类工单类型的id
                        parentId = row.idStr;
                        childValue = '';
                        $('#' + csSmOrderTypeChildComboboxId).combobox('clear');
                        $('#' + csSmOrderTypeChildComboboxId).combobox('reload');
                        selectFalg = true;
                    },
                onClick : params && params.onClick ? params.onClick
                    : undefined,
                onChange : params && params.onChange ? params.onChange
                    : undefined,
                onLoadSuccess : params && params.onLoadSuccess ? params.onLoadSuccess
                    : undefined,
                onBeforeLoad : params && params.onBeforeLoad ? params.onBeforeLoad
                    : function (param) {
                        debugger;
                        param.type=1;
                        if(pageStatus != 3){
                            param.rejectParentName = "留仓件";
                        }
                        if(params && params.data && !isEmptyObject(params.data)){
                            for (var key in params.data) {
                                param[key]=params.data[key];
                            }
                        }
                    },
                onLoadError : params && params.onLoadError ? params.onLoadError
                    : undefined,
                onShowPanel : params && params.onShowPanel ? params.onShowPanel
                    : function(){
                        if(uce.isNull($(this).combogrid("getValue"))){
                            var comgrid = $(this).uceCombogrid("grid");
                            $.data(comgrid[0]).originalRows =$.extend([],$.data(comgrid[0]).allRows);
                            filterRows = $.data(comgrid[0]).originalRows;
                            comgrid.datagrid('loadData', filterRows);
                        }
                    },
                onHidePanel : params && params.onHidePanel ? params.onHidePanel
                    : function(){
                        debugger;
                        if(!selectFalg){
                            //获取父类工单类型的id
                            parentId = $(this).combogrid("getValue");
                            if(uce.isNull($(this).combogrid("getValue"))){
                                parentId = 0;
                            }
                            childValue = '';
                            $('#' + csSmOrderTypeChildComboboxId).combobox('clear');
                            $('#' + csSmOrderTypeChildComboboxId).combobox('reload');
                        }
                        selectFalg = false;
                    }
            });

    $('#'+csSmOrderTypeChildComboboxId).uceCombobox({
        valueField : params && params.valueField ? params.valueField : 'idStr',
        textField : params && params.textField ? params.textField : 'name',
        url : params && params.url ? params.url :G_CTX_PATH+'/cs/CsSmOrderType/getCsSmOrderTypeList.do',
        method: params && params.method ? params.method : 'post',
        editable : params && params.editable == true ? true : false,
        onBeforeLoad:function(param){
            param.type=2;
            param.parentId = parentId;
        },
        onSelect: function(param){
            if(params && params.childUserMethod){
                params.childUserMethod(param,params);
            }
        },
        onLoadSuccess:function () {
            if(childValue != ''){
                $('#' + csSmOrderTypeChildComboboxId).combobox('setValue', childValue);
            }
            //2018-07-28
            if(params.orderChildTypeValue){
                $('#' + csSmOrderTypeChildComboboxId).combobox('setValue', params.orderChildTypeValue);
            }
        }
    });
}

/*
** @Author: may
 * @Description: 增加--请选择--选项
 * @Date: 2018/5/28 15:04
 * @Param:target目标元素,data数据
 * @return:
*/
function addHeaderData(target, data){
    var options = $(target).uceCombobox('options');
    if(options.headerData == null && options.headerText == null  && options.headerValue == null) {
        return data;
    }
    var headerData = options.headerData;
    if (!headerData) {
        if (options.headerValue == null) {
            options.headerValue = 0;
        }
        if (options.headerText == null) {
            options.headerText = '--请选择--';
        }
        if (typeof options.headerValue == 'string') {
            headerDataStr = "{\"" + options.valueField + "\":\"" + options.headerValue + "\",\"" + options.textField + "\":\"" + options.headerText + "\"}";
        } else {
            headerDataStr = "{\"" + options.valueField + "\":" + options.headerValue + ",\"" + options.textField + "\":\"" + options.headerText + "\"}";
        }

        headerData = eval('(' + headerDataStr + ')');
        options.headerData = headerData;
    }
    if (typeof data == "undefined") {
        data = [];
    }
    if (headerData.length) {
        $.each(headerData, function(index, headerRow) {
            if ($.inArray(headerRow, data) < 0) {
                data.splice(0,0, headerRow);
            }
        });
    } else {
        if ($.inArray(headerData, data) < 0) {
            data.splice(0,0, headerData);
        }
    }
    return data;
}
/**
 * 小写字母转大写
 * zhaocan2018-06-05
 */
function fnKeyUp(){
    this.value=this.value.toUpperCase();
}

/**
 * 使用js对象的方式构建form参数
 */
(function ($) {
    $.fn.serializeJson = function () {
        var serializeObj = {};
        $(this.serializeArray()).each(function () {
            serializeObj[this.name] = this.value;
        });
        return serializeObj;
    };
})(jQuery);

function formatterDate(date) {
    var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
    var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0"
    + (date.getMonth() + 1);
    var hor = date.getHours();
    var min = date.getMinutes();
    var sec = date.getSeconds();
    return date.getFullYear() + '-' + month + '-' + day+" "+hor+":"+min+":"+sec;
}

/*定责页面的定责datagrid数据获取*/
function getData(dg) {
    debugger;
    endEdit(dg);
    var data = $("#" + dg).datagrid('getData');
    var m = new Map();
    m.set("data", data.rows);
    return m;
}
function endEdit(dg){
    var rows = $("#" + dg).datagrid('getRows');
    for ( var i = 0; i < rows.length; i++) {
        $("#" + dg).datagrid('endEdit', i);
    }
}


/**
 * 格式化日期
 * @param value
 * @returns {string}
 */
function formatDate(value) {
    if (value == null) {
        return '';
    }
    var val = new Date(value);
    var year = parseInt(val.getYear()) + 1900;
    var month = parseInt(val.getMonth()) + 1;
    month = month > 9 ? month : ('0' + month);
    var date = parseInt(val.getDate());
    date = date > 9 ? date : ('0' + date);
    var time = year + '-' + month + '-' + date;
    return time;
}

/***
 * 加载省、市、县、乡镇四级联动方法
 * author:zhaocan
 * date:2018/6/27
 * **/
function pcrtAreaCascade(provinceId, cityId, regionId,townId,params) {
    var url = G_CTX_PATH + "/omg/OmgArea/getAreaCascade.do";
    if (!provinceId) {
        console.error("provinceId不能为空");
        return;
    }
    $("#" + provinceId).combobox({
        valueField: params && params.valueField ? params.valueField : 'areaCode',
        textField: params && params.textField ? params.textField : 'areaName',
        url: params && params.url ? params.url : url,
        editable: params && params.editable == false ? false : true,
        onBeforeLoad: function (param) {
            param.areaType = 2;
        },
        onLoadSuccess:function (data) {
            if(params.provinceValue){
                $('#' + provinceId).combobox('setValue', params.provinceValue);
            }else{
                $("#" + cityId).combobox('clear');
                $("#" + regionId).combobox('clear');
                $("#" + townId).combobox('clear');
                $("#" + cityId).combobox('loadData', {});
                $("#" + regionId).combobox('loadData', {});
                $("#" + townId).combobox('loadData', {});
            }
        },
        onSelect: !cityId || cityId == null ? function () {
        } : function (record) {
            console.log(record);
            if (cityId && cityId != null) {
                $("#" + cityId).combobox('clear');
                $("#" + cityId).combobox('loadData', {});
            }
            if (regionId && regionId != null) {
                $("#" + regionId).combobox('clear');
                $("#" + regionId).combobox('loadData', {});
            }
            if (townId && townId != null) {
                $("#" + townId).combobox('clear');
                $("#" + townId).combobox('loadData', {});
            }
            //2018-07-27
            if(!(params.provinceValue && params.provinceValue==record.areaCode)){
                params.cityValue="";
                params.regionValue="";
                params.townValue="";
            }
            $("#" + cityId).combobox({
                valueField: params && params.valueField ? params.valueField : 'areaCode',
                textField: params && params.textField ? params.textField : 'areaName',
                url: params && params.url ? params.url : url,
                editable: params && params.editable == true ? true : false,
                onBeforeLoad: function (param) {
                    param.areaType = 3;
                    param.parentAreaCode = record.areaCode;
                },
                onLoadSuccess:function (data) {
                    if(params.cityValue){
                        $('#' + cityId).combobox('setValue', params.cityValue);
                    }else{
                        $("#" + regionId).combobox('clear');
                        $("#" + townId).combobox('clear');
                        $("#" + regionId).combobox('loadData', {});
                        $("#" + townId).combobox('loadData', {});
                    }
                },
                onSelect: !regionId || regionId == null ? function () {
                } : function (record) {
                    if (regionId && regionId != null) {
                        $("#" + regionId).combobox('clear');
                        $("#" + regionId).combobox('loadData', {});
                    }
                    if (townId && townId != null) {
                        $("#" + townId).combobox('clear');
                        $("#" + townId).combobox('loadData', {});
                    }
                    //2018-07-27
                    if(!(params.cityValue && params.cityValue==record.areaCode)){
                        params.regionValue="";
                        params.townValue="";
                    }
                    $("#" + regionId).combobox({
                        valueField: params && params.valueField ? params.valueField : 'areaCode',
                        textField: params && params.textField ? params.textField : 'areaName',
                        url: params && params.url ? params.url : url,
                        editable: params && params.editable == true ? true : false,
                        onBeforeLoad: function (param) {
                            param.areaType = 4;
                            param.parentAreaCode = record.areaCode;
                        },
                        onLoadSuccess:function (data) {
                            if(params.regionValue){
                                $('#' + regionId).combobox('setValue', params.regionValue);
                            }else{
                                $("#" + townId).combobox('clear');
                                $("#" + townId).combobox('loadData', {});
                            }
                        },
                        onSelect: !townId || townId == null ? function () {
                        } : function (record) {
                            if (townId && townId != null) {
                                $("#" + townId).combobox('clear');
                                $("#" + townId).combobox('loadData', {});
                            }
                            //2018-07-27
                            if(!(params.regionValue && params.regionValue==record.areaCode)){
                                params.townValue="";
                            }
                            $("#" + townId).combobox({
                                valueField: params && params.valueField ? params.valueField : 'areaCode',
                                textField: params && params.textField ? params.textField : 'areaName',
                                url: params && params.url ? params.url : url,
                                editable: params && params.editable == true ? true : false,
                                onBeforeLoad: function (param) {
                                    param.areaType = 5;
                                    param.parentAreaCode = record.areaCode;
                                },
                                onLoadSuccess:function (data) {
                                    if(params.townValue){
                                        $('#' + townId).combobox('setValue', params.townValue);
                                    }
                                }
                            });
                        }

                    })
                }
            })
        }

    })
}

//查询时间校验
function dateboxOnSelect(d) {
    $(".panel .combo-p").css("display","none");
    d=new Date(d).getTime();
    var nowDate = new Date().getTime();
    if(d>nowDate){
        showInfoMsg('请不要选择未来日期');
        $("#"+this.id).datebox("setValue",formatterDate(new Date()));
    }
    var issd = this.id == 'querySTimeForCreate';
    var sd = new Date($('#querySTimeForCreate').datebox('getValue')).getTime();
    var ed = new Date($('#queryETimeForCreate').datebox('getValue')).getTime();
    if(ed<sd) {
        message : '结束日期小于开始日期';
        //只要选择了日期，不管是开始或者结束都对比一下，如果结束小于开始，则清空结束日期的值并弹出日历选择框
        $('#queryETimeForCreate').datebox('setValue', formatterDate(new Date()));
    }
}

//查询时间校验
function dateboxTaskOnSelect(d) {
    //panel combo-p
    $(".panel .combo-p").css("display","none");
    d=new Date(d).getTime();
    var nowDate = new Date().getTime();
    if(d>nowDate){
        showInfoMsg('请不要选择未来日期');
        $("#"+this.id).datebox("setValue",formatterDate(new Date()));
    }
    var sd = new Date($('#querySTimeFortaskCTime').datebox('getValue')).getTime();
    var ed = new Date($('#queryETimeFortaskCTime').datebox('getValue')).getTime();
    if(ed<sd) {
        showInfoMsg('结束日期小于开始日期');
        //只要选择了日期，不管是开始或者结束都对比一下，如果结束小于开始，则清空结束日期的值并弹出日历选择框
        //$('#queryETimeFortaskCTime').datebox('setValue', '').datebox('showPanel');
        $('#queryETimeFortaskCTime').datebox('setValue', formatterDate(new Date()));
    }
}


/**
 * 同步ajax请求
 * @author may
 * @date 2018年7月9日15:35:32
 */
function uceAjaxAsync (url, data, callback, type, async){
    if (!type) {
        type = 'POST';
    }

    if(async == null){
        async = true;
    }
    $.ajax({
        type: type,
        url: url,
        data: data,
        async: async,
        success : function(data){
            var result = data;
            if (typeof data == 'string') {
                result = eval('('+ data +')');
            }
            if (result.message) {
                result.success ? showTips(result.message,'success') : showError(result);
            }
            if(callback){
                callback.apply(this, [result]);
            }
        }
    });
}

/**
 * id:table id,如：<table id="test" class="easyui-datagrid">
 * columns:显示的列配置项,如:[[{field:'name',title: '属性名称',align: 'center'},{field:'age',title: '年龄',width: 50}]]
 * dataGridParams:datagrid相关的参数配置项，详见easyuiAPI-datagrid;
 */
function icsloadGrid(id,columns,dataGridParams){
    if(id ==null || columns==null || dataGridParams.url==null){
        console.error("datagrid id、colums、url不能为空！");
        return;
    };
    if (dataGridParams.pageSize!=null && dataGridParams.pageSize != undefined) {
        if(!isNaN(dataGridParams.pageSize)){
            dataGridParams.pageList=[dataGridParams.pageSize,dataGridParams.pageSize*2,dataGridParams.pageSize*3,dataGridParams.pageSize*4,dataGridParams.pageSize*5,dataGridParams.pageSize*10]
            dataGridParams.pagination = 'true';
        }else{
            console.error("pageSize必须要为数字！");
            return;
        }
    }

    $('#'+id).datagrid({
        remoteSort : dataGridParams.remoteSort ? dataGridParams.remoteSort : false,
        title: dataGridParams.title ? dataGridParams.title : '',
        /*		width: dataGridParams.width ? dataGridParams.width : 'auto',
         height: dataGridParams.height ? dataGridParams.height : 'auto',*/
        url: dataGridParams.url,
        method: dataGridParams.method =='get' ? 'get' : 'post',
        queryParams: dataGridParams.queryParams ? dataGridParams.queryParams : {},//请求参数对象{a:'1'}
        columns:columns, //列配置项
        striped: true , //是否显示斑马线效果。
        collapsible:false,//表格是否可折叠
        singleSelect : dataGridParams.singleSelect == 'true' ? true : false,  //允许单行选择true/false
        fitColumns: dataGridParams.fitColumns == 'true' ? true : false, //真正的自动展开/收缩列的大小，以适应网格的宽度，防止水平滚动。
        loadMsg:'数据加载中请稍后……',
        pagination: dataGridParams.pagination =='true' ? true : false,  //如果为true，则在DataGrid控件底部显示分页工具栏。
        pagePosition:'bottom',//定义分页工具栏的位置。可用的值有：'top','bottom','both'。
        rownumbers: dataGridParams.rownumbers=='false' ? false : true, //如果为true，则显示一个行号列。
        pageNumber : 1, //在设置分页属性的时候初始化页码。
        pageSize: dataGridParams.pageSize ? dataGridParams.pageSize : 10,//在设置分页属性的时候初始化页面大小。
        pageList: dataGridParams.pageList ? dataGridParams.pageList : [10,20,30,40,50,100],//在设置分页属性的时候 初始化页面大小选择列表。
        nowrap: dataGridParams.nowrap=='false' ? false : true, //如果为true，则在同一行中显示数据。设置为true可以提高加载性能。
        resizable: true, //如果为true，允许列改变大小。
        rownumberWidth : !isNaN(dataGridParams.rownumberWidth) ? dataGridParams.rownumberWidth : 50,
        toolbar: dataGridParams.toolbar ? dataGridParams.toolbar : [], //顶部工具栏的DataGrid面板
        onBeforeLoad: dataGridParams.onBeforeLoad ? dataGridParams.onBeforeLoad : function(param){
            //在载入请求数据数据之前触发，如果返回false可终止载入数据操作。
            console.log('onBeforeLoad');
        },
        onLoadSuccess: dataGridParams.onLoadSuccess ? dataGridParams.onLoadSuccess : function(data){
            //在数据加载成功的时候触发
            console.log('onLoadSuccess');
        },
        onSelect:dataGridParams.onSelect ? dataGridParams.onSelect :function(){
            console.log('onSelect');
        }
    });
}

/**
 * 打开dialog
 * @param id
 * @param title
 * @param dlHeight
 * chenqinglong
 */
function icsOpenDialog(id, title,dlHeight) {
	//var h = parent.$("#mainTab")[0].offsetHeight;
    var h = 700;
	try {
		h = parent.$("#mainTab")[0].offsetHeight;
	} catch(err) {

	}
    $('#'+id).dialog({
        title: title,
        align : 'center',
        // 弹框top=滚动条到页面顶部的距离+（页面显示的高度-弹框的高度）/2
        top:$(document).scrollTop()+(h-dlHeight)*0.5,
        cache: false,
        modal: true
    });
    $('#'+id).dialog('open');
}

/**
 * 根据处理截至时间获取剩余处理时长
 * 算法：
 * 1、若处理截至时间为空，返回“-”；
 * 2、若处理截至时间小于当前时间，直接返回0
 * 3、若处理截至时间小于当前时间,处理截至时间 减 当前时间
 * @param deadline
 * @author chenqinglong
 */
function getRemainingHandleDuration(deadline){
    var result = "-";
    if(deadline != null && deadline != "") {
        var deadlineDate = new Date(deadline.replace("-", "/").replace("-", "/"));
        var nowDate = new Date();
        if (deadlineDate < nowDate) {
            result = 0;
        } else {
            var timeDifference = deadlineDate.getTime() - nowDate.getTime(); //时间差的毫秒数
            //计算出相差天数
            var days = Math.floor(timeDifference / (24 * 3600 * 1000));
            //计算出小时数
            var leave1 = timeDifference % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
            var hours = Math.floor(leave1 / (3600 * 1000));
            //计算相差分钟数
            var leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
            var minutes = Math.floor(leave2 / (60 * 1000));
            result = ((days == 0 || days == "") ? "" : days + "天") + ((hours == 0 || hours == "") ? "" : hours + "小时") + ((minutes == 0 || minutes == "") ? "" : minutes + "分钟");
        }
    }
    return result;
}

/**
 * @Author: zhangwei
 * 根据投诉编号渲染申诉模块html
 * @param acoCode
 */
function renderAppealInfo(acoCode){
    //先隐藏申诉accordion
    $('#'+'onceAppeal_'+'appealAccordionId').hide();
    $('#'+'twiceAppeal_'+'appealAccordionId').hide();
    if(isHasAppeal(acoCode)){
        //存在该投诉的申诉记录，循环添加申诉模块（一对多），并且赋值
        var data ={acoCode:acoCode};
        var url=G_CTX_PATH+"/cs/CsWoArbitrationAppeal/getArbitrationAppealByAcoCode.do";
        $.ajax({
            type: 'post',
            url: url,
            data:data,
            success: function (data) {
                $.each(data, function (index, row) {
                    if(index ==0){
                        renderAppealData('onceAppeal_',data[index]);
                    }else{
                        renderAppealData('twiceAppeal_',data[index]);
                    }
                });
            }
        });
    }else{
        //不存在申诉信息，隐藏Accordion
        $('#'+'onceAppeal_'+'appealAccordionId').hide();
        $('#'+'twiceAppeal_'+'appealAccordionId').hide();
    }
}
/**
 * @Author: zhangwei
 * 赋值
 * @param data
 */
function renderAppealData(idAppend,data){
    $('#'+idAppend+'appealAccordionId').show();
    //申诉信息隐藏
    $('#'+idAppend+'appealInfoAccordionId').hide();
    //申诉信息
    $('#'+idAppend+'code').textbox('setValue',data.code);
    $('#'+idAppend+'appealOrgName').textbox('setValue',data.appealOrgName);
    $('#'+idAppend+'appealFinanceName').textbox('setValue',data.appealFinanceName);
    $('#'+idAppend+'appealerName').textbox('setValue',data.appealerName);
    $('#'+idAppend+'appealReason').textbox('setValue',data.appealReason);
    //定责信息
    uceAjax(G_CTX_PATH + '/cs/CsWoArbitrationAppeal/getAaoByCode.do', {aaoCode: data.code}, function (result) {
        result = result.data;
        if (result != null && result != "") {
            //赋值
            $('#'+idAppend+'beComplainantBranchTypeId').combobox('setValue',getTypeNameByCode("TYPE_OF_COMLAINT_NETWORK",result.beComplainantBranchType));
            $('#'+idAppend+"beComplainantFineSumId").textbox("setValue",result.beComplainantFineSum);
            $('#'+idAppend+"beComplainantCenterTypeId").combobox('setValue', getTypeNameByCode("TYPE_COMPLANTIS",result.beComplainantCenterType));
            $('#'+idAppend+"dutyTypeId").combobox('setValue', getTypeNameByCode("COMPALINTS_RESPONSITITY_TYPE",result.dutyType));
            $('#'+idAppend+"complainantDepartId").combobox('setValues', result.complainantDepart);
            $('#'+idAppend+"compensationSumId").textbox('setValue', result.compensationSum);
            $('#'+idAppend+"dutyBranchId").combobox('setValue', result.dutyBranchName);
            $('#'+idAppend+"claimNumId").textbox('setValue', result.claimNum);
            $('#'+idAppend+"dutyBranchFineSumId").textbox('setValue', result.dutyBranchFineSum);
            $('#'+idAppend+"dealWithPeopleId").textbox("setValue",result.currentDealEmpName);
            $('#'+idAppend+"dealWithTimeId").textbox("setValue",formatTimeYMD(result.submitTime));
        } else {
            $('#'+idAppend+'appealDutyInfoAccordionId').hide();
            $('#'+idAppend+'appealAccordionId').hide();
        }
    }, "GET");
}
/**
 * @Author: zhangwei
 * 判断是否存在申诉
 * @returns {boolean}
 */
function isHasAppeal(){
    var rs=false;
    $.ajax({
        type: "POST",
        url: G_CTX_PATH+'/cs/CsWoArbitrationComplaints/isHasAppeal.do',
        data: {code:codesId},
        async: false,
        success : function(result){
            rs=result;
        }
    });
    return rs;
}
/* *
 * @Author: zhangwei
 * @Description: 工单系统消息公共方法--初始化
 * @Date: 2018/8/7 14:06
 * @Param: code 显示的工单编号 hiddenCode 隐藏的工单参数编号
 *         querySTimeForCreate 查询时间开始id
 *         queryETimeForCreate 查询时间结束id
 *         withTime 是否需要封装时间段 false/不需要  true/需要
 * @return:
 */
function initMsgCode(code,hiddenCode,querySTimeForCreate,queryETimeForCreate,withTime) {
	debugger;
    var totalMsgflag = $('#totalMsgflag').val();
    var woCode = $('#' + hiddenCode).val();
    if(totalMsgflag !="" && totalMsgflag!=null ){
        $('#'+querySTimeForCreate).datebox('setValue', '');
        $('#'+queryETimeForCreate).datebox('setValue', '');
		//消息体总数提醒跳转默认工单
		try {
			clearBillCodes1();
		}catch (e) {
		}
    }else if(woCode !="" && woCode!=null ){
    	if($('#'+code)){
            $('#'+code).textbox('setValue',woCode);
    	}
    	if($('#woCodes')){
            $('#woCodes').val(woCode);
    	}
        try {
            clearBillCodes1();
        }catch (e) {
        }
    }else if(withTime){
        $('#'+querySTimeForCreate).datebox('setValue', formatterDate(new Date()));
        $('#'+queryETimeForCreate).datebox('setValue', formatterDate(new Date()));
    }else{
        return ;
    }
}
/* *
 * @Author: zhangwei
 * @Description: 工单系统消息公共方法--设置初始化查询条件
 * @Date: 2018/8/7 14:07
 * @Param:  hiddenCode 隐藏的工单参数编号
 *         querySTimeForCreate 查询时间开始id
 *         queryETimeForCreate 查询时间结束id
 *         withTime 是否需要封装时间段 false/不需要  true/需要
 * @return:
 */
function initQueryParams(woCodeHidden,querySTimeForCreate,queryETimeForCreate,dataGridParams) {
	debugger;
    var totalMsgflag = $('#totalMsgflag').val();
    var woCode = $('#' + woCodeHidden).val();
    var querySTimeFortaskCTime2 = $('#' + querySTimeForCreate).datebox('getValue');
    var queryETimeFortaskCTime2 = $('#' + queryETimeForCreate).datebox('getValue');
    if(totalMsgflag !="" && totalMsgflag!=null ){
        dataGridParams.queryParams={};
    }else if(woCode !="" && woCode!=null ){
        dataGridParams.queryParams={code:woCode};
    }else{
        dataGridParams.queryParams={
            querySTimeForCreate:querySTimeFortaskCTime2,
            queryETimeForCreate:queryETimeFortaskCTime2,
            //存在冗余，动态拼接比较繁琐
            querySTimeFortaskCTime:querySTimeFortaskCTime2,
            queryETimeFortaskCTime:queryETimeFortaskCTime2
        }
    }
}

/**
 * 加载等待
 */
function ajaxLoading(alertMessage){
    alertMessage = (alertMessage == "" || alertMessage == null || alertMessage == undefined) ? "正在处理，请稍候。。。" : alertMessage;
    $("<div class=\"datagrid-mask\" style='z-index: 10000;position: fixed;'></div>").css({display:"block",width:"100%",height:$(window).height()}).appendTo("body");
    $("<div class=\"datagrid-mask-msg\" style='z-index: 10100;position: fixed;'></div>").html(alertMessage).appendTo("body").css({display:"block",left:($(document.body).outerWidth(true) - 190) / 2,top:($(window).height() - 45) / 2});
}
/**
 * 取消加载等待
 */
function ajaxLoadEnd(){
    $(".datagrid-mask").remove();
    $(".datagrid-mask-msg").remove();
}

/**
 * 组织架构查询动态加载
 * @param departId 机构元素id
 * @param param eg:{orgTypeStr:"20,21,30,40",defaultOrgType:"20"}  仅支持此种参数，请严格传递参数
 */
function  initDepartComboDB(departId,param,title) {
    var prompt ="";
    if(title){
        prompt=title;
    }
    $("#"+departId).combobox({
        url: G_CTX_PATH + '/cs/omg/org/findOrgCmsByOrgTypeAllStatusDB.do',
        prompt: prompt,
        queryParams: param,
        mode:'remote',
        valueField: 'baseOrgCode',
        textField: 'orgFullName',
    })
}

/**
 * 修改方法 martin
 * @param departId
 * @param param
 * @param title
 */
function  initDepartComboDBSecond(departId,param,title) {
    var prompt ="";
    if(title){
        prompt=title;
    }
    $("#"+departId).combobox({
        url: G_CTX_PATH + '/cs/omg/org/findOrgCmsByOrgTypeAllStatusDB.do',
        prompt: prompt,
        queryParams: param,
        mode:'remote',
        valueField: 'baseOrgCode',
        textField: 'orgFullName',
        onBeforeLoad: function(param){
            if(param == null || param.q == null || param.q.replace(/ /g, '') == ''){
                var value = $(this).combobox('getValue');
                if(value){// 修改的时候才会出现q为空而value不为空
                    param.q = value;
                    return true;
                }
                return false;
            }
        }
    })
}

function orgCombogrid(domId, params) {
	console.log('加载机构下拉框');
	if (!domId) {
		console.error("domId不能为空！");
		return;
	}
	if (params && params.pageSize != null && params.pageSize != undefined) {
		if (!isNaN(params.pageSize)) {
			params.pageList = [ params.pageSize, params.pageSize * 2,
					params.pageSize * 3, params.pageSize * 4,
					params.pageSize * 5, params.pageSize * 10 ]
			params.pagination = true;
		} else {
			console.error("pageSize必须要为数字！");
			return;
		}
	}
	$("#" + domId)
			.combogrid(
					{
						url : params && params.url ? params.url
								: G_CTX_PATH+'/cs/omg/org/findCmsBaseOrgByPage.do',
						queryParams : params && params.queryParams ? params.queryParams
								: undefined,
						columns : params && params.columns ? params.columns
								: [ [ {
									field : 'orgType',
									hidden : true
								}, {
									field : 'baseOrgCode',
									hidden : true
								}, {
									field : 'orgCode',
									title : '机构编号',
									align : 'left',
									width : 100
								}, {
									field : 'orgName',
									title : '机构名称',
									align : 'left',
									width : 250
								} ] ],
						pagination : params && params.pagination == false ? false
								: true,
						pageNumber : 1,
						pageSize : params && params.pageSize
								&& !isNaN(params.pageSize) ? params.pageSize
								: undefined,
						pageList : params && params.pageList ? params.pageList
								: undefined,
						idField : params && params.idField ? params.idField
								: 'baseOrgCode',
						textField : params && params.textField ? params.textField
								: 'orgName',
						mode : params && params.mode == 'local' ? 'local'
								: 'remote',
						loadMsg : '数据加载中请稍后……',
						panelWidth : params && params.panelWidth
								&& !isNaN(params.panelWidth) ? params.panelWidth
								: 350,
						panelHeight : params && params.panelHeight
								&& !isNaN(params.panelHeight) ? params.panelHeight
								: 320,
						singleSelect : params && params.singleSelect == true ? true
								: false,
						fitColumns : true,
						onSelect : params && params.onSelect ? params.onSelect
								: undefined,
						onClick : params && params.onClick ? params.onClick
								: undefined,
						onChange : params && params.onChange ? params.onChange
								: undefined,
						onLoadSuccess : params && params.onLoadSuccess ? params.onLoadSuccess
								: undefined,
						onBeforeLoad : params && params.onBeforeLoad ? params.onBeforeLoad
								: undefined,
						onLoadError : params && params.onLoadError ? params.onLoadError
								: undefined,
						onHidePanel : params && params.onHidePanel ? params.onHidePanel
								: function() {
									var g = $(this).combogrid('grid'); // get
									var r = g.datagrid('getSelected'); // get
									if (null != g || g.length > 0) {
										if (null == r || r.length == 0) {
											$(this).combogrid('clear');
											$(this).combogrid('setValue', '');
										} else {
											$(this).combogrid('setValue',
													r.baseOrgCode);
										}
									}
								},
						onShowPanel : function() {
							/* 解决datagrid q值、页码缓存问题, */
							var q = $(this).combogrid('getValue');
							if (!q) {
								if (params && params.queryParams) {
									var queryParams = params.queryParams;
									queryParams['q'] = '';
									$(this).combogrid("grid").datagrid(
											"reload", queryParams);
									$(this).combogrid("grid").datagrid(
											'gotoPage', 1);
								} else {
									$(this).combogrid("grid").datagrid(
											"reload", {
												'q' : ''
											});
									$(this).combogrid("grid").datagrid(
											'gotoPage', 1);
								}
							}
						}
					})
}
/**
 * 根据当前登录的机构查询下级网点
 * @param domId
 * @param params
 */
function orgForOrgCodeCombogrid(domId, params) {
	console.log('加载机构下拉框');
	if (!domId) {
		console.error("domId不能为空！");
		return;
	}
	if (params && params.pageSize != null && params.pageSize != undefined) {
		if (!isNaN(params.pageSize)) {
			params.pageList = [ params.pageSize, params.pageSize * 2,
					params.pageSize * 3, params.pageSize * 4,
					params.pageSize * 5, params.pageSize * 10 ]
			params.pagination = true;
		} else {
			console.error("pageSize必须要为数字！");
			return;
		}
	}
	$("#" + domId)
			.combogrid(
					{
						url : params && params.url ? params.url
								: G_CTX_PATH+'/cs/omg/org/findOrgByOrgCode.do',
						queryParams : params && params.queryParams ? params.queryParams
								: undefined,
						columns : params && params.columns ? params.columns
								: [ [ {
									field : 'orgType',
									hidden : true
								}, {
									field : 'baseOrgCode',
									hidden : true
								}, {
									field : 'orgCode',
									title : '机构编号',
									align : 'left',
									width : 100
								}, {
									field : 'orgName',
									title : '机构名称',
									align : 'left',
									width : 250
								} ] ],
						pagination : params && params.pagination == false ? false
								: true,
						pageNumber : 1,
						pageSize : params && params.pageSize
								&& !isNaN(params.pageSize) ? params.pageSize
								: undefined,
						pageList : params && params.pageList ? params.pageList
								: undefined,
						idField : params && params.idField ? params.idField
								: 'baseOrgCode',
						textField : params && params.textField ? params.textField
								: 'orgName',
						mode : params && params.mode == 'local' ? 'local'
								: 'remote',
						loadMsg : '数据加载中请稍后……',
						panelWidth : params && params.panelWidth
								&& !isNaN(params.panelWidth) ? params.panelWidth
								: 350,
						panelHeight : params && params.panelHeight
								&& !isNaN(params.panelHeight) ? params.panelHeight
								: 320,
						singleSelect : params && params.singleSelect == true ? true
								: false,
						fitColumns : true,
						onSelect : params && params.onSelect ? params.onSelect
								: undefined,
						onClick : params && params.onClick ? params.onClick
								: undefined,
						onChange : params && params.onChange ? params.onChange
								: undefined,
						onLoadSuccess : params && params.onLoadSuccess ? params.onLoadSuccess
								: undefined,
						onBeforeLoad : params && params.onBeforeLoad ? params.onBeforeLoad
								: undefined,
						onLoadError : params && params.onLoadError ? params.onLoadError
								: undefined,
						onHidePanel : params && params.onHidePanel ? params.onHidePanel
								: function() {
									var g = $(this).combogrid('grid'); // get
									var r = g.datagrid('getSelected'); // get
									if (null != g || g.length > 0) {
										if (null == r || r.length == 0) {
											$(this).combogrid('clear');
											$(this).combogrid('setValue', '');
										} else {
											$(this).combogrid('setValue',
													r.baseOrgCode);
										}
									}
								},
						onShowPanel : function() {
							/* 解决datagrid q值、页码缓存问题, */
							var q = $(this).combogrid('getValue');
							if (!q) {
								if (params && params.queryParams) {
									var queryParams = params.queryParams;
									queryParams['q'] = '';
									$(this).combogrid("grid").datagrid(
											"reload", queryParams);
									$(this).combogrid("grid").datagrid(
											'gotoPage', 1);
								} else {
									$(this).combogrid("grid").datagrid(
											"reload", {
												'q' : ''
											});
									$(this).combogrid("grid").datagrid(
											'gotoPage', 1);
								}
							}
						}
					})
}

/**
 * 对Date的扩展，将 Date 转化为指定格式的String
 * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 * (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 * (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
 * @author Sunny 2018-10-07
 * @param fmt
 * @returns {*}
 */
Date.prototype.format = function (fmt) {
    //author: meizz
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "h+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}

/**
 * 验证扩展
 * @author Sunny 2018-10-07
 */
$.extend($.fn.validatebox.defaults.rules, {
    //验证只能输入数字范围
    limit:{
        validator: function (value,param) {
            debugger;
            var min = param[0];
            var max = param[1];
            if(value >= min && value <= max){
                return true;
            }
            return false;
        },
        message: '请输入正确范围'
    },
    //验证只能输入小数和非0的正整数
    weight:{
        validator: function (value) {
            var regex = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^[0-9]\.[0-9]([0-9])?$)/;
            regex.test(value);
        },
        message: '请输入正确格式'
    }
})

/**
 * 取消必填字段
 * @param objArr
 */
function unSetRequires(objArr) {
    $.each(objArr,function(index,obj){
        $("#"+obj).parents("div.acc-items").find("div.acc-title").find("span").text("");
        if($("#"+obj+".easyui-combobox").length== 1){
            $("#"+obj).combobox({required: false});
        }else if($("#"+obj+".easyui-textbox").length== 1){
            $("#"+obj).textbox({required: false});
        }
    })
}

/**
 * 设置必填字段
 * @param objArr
 */
function setRequires(objArr) {
    $.each(objArr,function(index,obj){
        $("#"+obj).parents("div.acc-items").find("div.acc-title").find("span").text("*");
        if($("#"+obj+".easyui-combobox").length== 1){
            $("#"+obj).combobox({required: true});
        }else if($("#"+obj+".easyui-textbox").length== 1){
            $("#"+obj).textbox({required: true});
        }
    })
}



/**
 * 判读空对象
 * @author Sunny
 * @param str
 * @returns {boolean}
 */
var uce = {};
uce.isNull = function(str){
    if(typeof str == "undefined"){
        return true;
    }else if(str == null){
        return true;
    }else if(typeof str == "string" && (str === "" || str === "undefined" || str === "null")){
        return true;
    }else if(typeof str == "object" && $.isArray(str) && str.length == 0){
        return true;
    }else if(typeof str == "object" && $.isEmptyObject(str)){
        return true;
    }else{
        return false;
    }
}

/**
 * 设置必填字段
 * @param objArr
 * @param type = true 是否必填
 */
uce.setRequires = function(objArr,type){
    if(uce.isNull(type)){
        throw new Error("参数非法");
    }
    $.each(objArr,function(index,obj){
        $(obj).parents("div.acc-items").find("div.acc-title").find("span").text("*");
        if($(obj+".easyui-combobox").length== 1){
            $(obj).combobox({required: type});
        }else if($(obj+".easyui-textbox").length== 1){
            $(obj).textbox({required: type});
        }else if($(obj+".easyui-numberbox").length== 1){
            $(obj).textbox({required: type});
        }
    })
}
/**
 * 判断是否json对象
 * @author Sunny
 * @param obj
 * @returns {boolean}
 */
uce.isJson = function(obj){
    var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
    return isjson;
}

/**
 * 打开dialog
 * @param id
 * @param title
 */
function openDialog(id, title) {
	$('#' + id).dialog({
		title : title,
		iconCls:'icon-title',
		cache : false,
		modal : true,
		constrain:true,
		resizable:true,
		onLoad : function(){
		},
		onOpen : function() {
		},
		onBeforeOpen: function() {
			var formId = id.substr(4, id.length - 4);
			if ($('#form' + formId)) {
				$('#form' + formId).form('clear');
			}
		}
	});

	var dlgWidth = $('#' + id).dialog('options').width;
	var dlgHeight = $('#' + id).dialog('options').height;
	//add by xj crossDomain
	var winWidth = 800;
	var winHeight = 400;
	if(crossDomainFlag == true){
		winWidth = window.outerWidth;
		winHeight = window.outerHeight;
	}else{
		winWidth = $('.tabs-panels', parent.document).width();
		winHeight = $('.tabs-panels', parent.document).height();
	}
	//add by xj crossDomain
	var top =  $('#' + id).dialog('options').top;
	var left =  $('#' + id).dialog('options').left;

	if(dlgHeight >= winHeight){
		$('#' + id).dialog('resize',{height:winHeight-100,top:20})
	}
	if(dlgWidth >= winWidth){
		$('#' + id).dialog('resize',{width:winWidth-50,left:20})
	}

	//应对跨域问题
	if(top < 20){
		$('#' + id).dialog('resize',{width:winWidth-100,height:winHeight-180,top:20})
	}

	$('#' + id).dialog('open');
	$('#' + id).parents('.panel').css('position','fixed');
}

(function($){
    if($.fn.combobox){
        $.fn.combobox.defaults.inputEvents.blur=function(){
            var combo=$(this).closest(".combo").prev();//因为它是隐藏本来的元素，创建easyui的元素，所以得先找到我定义的那个combobox
            var value = combo.combobox("getValue");//取得combobox的值
            var text = combo.combobox("getText");//取得combobox的文本
            if (!value ||text == value) {
                combo.combobox("clear");
            }
        };
    }
})(jQuery);

function minigrid(id, columns, datagridParams) {
    $('#'+id).after("<div ><ul id='miniui-dg-contextmenu-"+id+"' class='mini-contextmenu'><li id='miniui-dg-contextmenu-copy-"+id+"' iconCls='icon-print'>复制</li></ul></div>");

    //导出设置按钮
    if($('#dg-export-set-button-' + id).length > 0) {
        $('#' + id).after("<div id = 'dg-export-set-div-" + id + "'><div id = 'dg-export-set-dlg-" + id + "' class='easyui-dialog' data-options = 'title:&apos;导出设置&apos;,closed:true,buttons:&apos;#dg-export-set-dlg-btn-"+id+"&apos;'><div class='easyui-layout' data-options='border:false' style='width:501px;height:300px'><div data-options='region:&apos;west&apos;,border:false'style='width:200px;'><div id='dg-export-set-datalist-west-" + id + "' ></div></div><div data-options='region:&apos;center&apos;,border:false' style='padding:50px 1px'><a class='easyui-linkbutton' id = 'dg-export-set-button-moveInAll-"+id+"'  data-options='width:99'>全部移入\>\></a><a id = 'dg-export-set-button-moveIn-"+id+"' class='easyui-linkbutton' data-options='width:99' style='width:&apos;100px&apos;,border:false'>移入\></a><a id = 'dg-export-set-button-moveOut-"+id+"' class='easyui-linkbutton' data-options='width:99'>移出\<</a><a id = 'dg-export-set-button-moveOutAll-"+id+"' class='easyui-linkbutton' data-options='width:99'>全部移出\<\<</a></div><div data-options='region:&apos;east&apos;' style='width:200px;'><div id='dg-export-set-datalist-east-" + id + "' ></div></div><div data-options='region:&apos;south&apos;' style='height:40px'><form id='dg-export-set-form-"+id+"' method='post'><input class='easyui-textbox' name='fileNameXls' data-options='prompt:&apos;请输入自定义文件名...&apos;' style='height:39px;width:499px'/></form></div></div></div><div id = 'dg-export-set-dlg-btn-" + id + "' style='padding-top:20px;'><a href='javascript:void(0)' id='dg-export-set-dlg-btn-save-"+id+"' class='easyui-linkbutton save'  >导出</a><a href='javascript:void(0)' id='dg-export-set-dlg-btn-cancel-"+id+"' class='easyui-linkbutton call' >取消</a></div></div>")
        $.parser.parse('#dg-export-set-div-'+id);

        function buildColumnList(columns, columnsFlat) {
            columns.map(function(item) {
                if(!item.columns) {
                    if(item.type != 'indexcolumn' && item.type != 'checkcolumn' && item.isExportColumn != false) {
                        columnsFlat.push({
                            header: item.header,
                            field: item.field
                        })
                    }
                } else {
                    buildColumnList(item.columns, columnsFlat);
                }
            })
            return columnsFlat;
        }

        var columnsFlat = [];
        buildColumnList(columns, columnsFlat);
        $('#dg-export-set-datalist-west-' + id).datalist({
            height:'100%',
            data: columnsFlat,
            textField: 'header',
            valueField: 'field',
            checkbox: true,
            singleSelect:false
        })
        $('#dg-export-set-datalist-east-' + id).datalist({
            height:'100%',
            data: [],
            textField: 'header',
            valueField: 'field',
            checkbox: true,
            singleSelect:false
        })

        //导出按钮点击事件
        $('#dg-export-set-button-' + id).linkbutton({
            onClick: function() {
                $('#dg-export-set-dlg-' + id).dialog('open')
            }
        })

        //dialog内按钮点击实际
        $('#dg-export-set-button-moveInAll-' + id).linkbutton({
            onClick : function(){
                var chooseItems = $('#dg-export-set-datalist-west-' + id).datalist('getRows');
                if(chooseItems != null){
                    var limit = chooseItems.length;
                    for(var i = 0 ; i < limit ; i++){
                        $('#dg-export-set-datalist-east-' + id).datalist('appendRow',chooseItems[0]);
                        $('#dg-export-set-datalist-west-' + id).datalist('deleteRow',$('#dg-export-set-datalist-west-' + id).datalist('getRowIndex',chooseItems[0]));
                    }
                }

            }
        })
        $('#dg-export-set-button-moveIn-' + id).linkbutton({
            onClick : function(){
                var chooseItems = $('#dg-export-set-datalist-west-' + id).datalist('getChecked');
                if(chooseItems != null){
                    var limit = chooseItems.length;
                    for(var i = 0 ; i < limit ; i++){
                        $('#dg-export-set-datalist-east-' + id).datalist('appendRow',chooseItems[i]);
                        $('#dg-export-set-datalist-west-' + id).datalist('deleteRow',$('#dg-export-set-datalist-west-' + id).datalist('getRowIndex',chooseItems[i]));
                    }
                }
            }
        })
        $('#dg-export-set-button-moveOutAll-' + id).linkbutton({
            onClick : function(){
                var chooseItems = $('#dg-export-set-datalist-east-' + id).datalist('getRows');
                if(chooseItems != null){
                    var limit = chooseItems.length;
                    for(var i = 0 ; i < limit ; i++){
                        $('#dg-export-set-datalist-west-' + id).datalist('appendRow',chooseItems[0]);
                        $('#dg-export-set-datalist-east-' + id).datalist('deleteRow',$('#dg-export-set-datalist-east-' + id).datalist('getRowIndex',chooseItems[0]));
                    }
                }
            }
        })
        $('#dg-export-set-button-moveOut-' + id).linkbutton({
            onClick : function(){
                var chooseItems = $('#dg-export-set-datalist-east-' + id).datalist('getChecked');
                if(chooseItems != null){
                    var limit = chooseItems.length;
                    for(var i = 0 ; i < limit ; i++){
                        $('#dg-export-set-datalist-west-' + id).datalist('appendRow',chooseItems[i]);
                        $('#dg-export-set-datalist-east-' + id).datalist('deleteRow',$('#dg-export-set-datalist-east-' + id).datalist('getRowIndex',chooseItems[i]));
                    }
                }
            }
        })
        $('#dg-export-set-dlg-btn-save-'+id).linkbutton({
            onClick: function(){
                if($('#dg-export-set-button-' + id).data('bfclick')){
                    var bfclick = eval($('#dg-export-set-button-' + id).data('bfclick')+"()")
                    if(bfclick == false){
                        return false;
                    }
                }
                var queryParams = {};
                if($('#dg-export-set-button-' + id).data('params')){
                    queryParams = eval($('#dg-export-set-button-' + id).data('params')+'()');
                }

                var exclusions = $('#dg-export-set-datalist-west-' + id).datalist('getRows');
                var exclusionTitles = [];
                exclusions.map(function(item){
                    exclusionTitles.push(item.header);
                })

                queryParams['exclusionTitles'] = JSON.stringify(exclusionTitles);

                $('#dg-export-set-form-'+id).form('submit',{
                    url:$('#dg-export-set-button-' + id).data('url'),
                    queryParams:queryParams
                })
                if($('#dg-export-set-button-' + id).data('afclick')){
                    eval($('#dg-export-set-button-' + id).data('afclick')+'()')
                }
                $('#dg-export-set-dlg-' + id).dialog('close');
            }

        })
        $('#dg-export-set-dlg-btn-cancel-'+id).linkbutton({
            onClick: function(){
                $('#dg-export-set-dlg-' + id).dialog('close');
            }
        })
    }

    mini.parse();
    var grid = mini.get(id);

    function dealColumns(columns){
        if(columns && columns.length > 0){
            columns.map(function(item){
                item.headerAlign = 'center';
                if(item.columns){
                    dealColumns(item.columns);
                }
            })
        }
    }
    dealColumns(columns);

    /**
     * ========================================propertie================================================
     */
    grid.set({
        columns: columns,
        url: datagridParams && datagridParams.url ? datagridParams.url : null,
        dataField: datagridParams && datagridParams.dataField ? datagridParams.dataField : 'rows',

        style: datagridParams && datagridParams.style ? datagridParams.style : "height:100%;",
        enableHotTrack: datagridParams && datagridParams.enableHotTrack == true ? true : false,//移动到行时高亮显示
        defaultRowHeight: 30,
        allowAlternating: true,

        allowCellSelect : datagridParams && datagridParams.selectType == 'row' ? false : true,
        //allowRowSelect : datagridParams && datagridParams.selectType == 'row' ? true : false,
        multiSelect: datagridParams && datagridParams.multiSelect == false ? false : true,

        //pageIndex: 1,
        //pageIndexField: 'page',
        pageSizeField: 'rows',
        pageSize: datagridParams && datagridParams.pageSize ? datagridParams.pageSize : 50,
        sizeList: datagridParams && datagridParams.sizeList ? datagridParams.sizeList : [50,100,150,200,250,500],

        allowSortColumn: datagridParams && datagridParams.allowSortColumn == false ? false : true,
        sortMode: datagridParams && datagridParams.sortMode ? datagridParams.sortMode : 'client',
        showSortIcon: datagridParams && datagridParams.showSortIcon == true ? true : false,
        sortDblClick: datagridParams && datagridParams.sortDblClick == true ? true : false,
        allowCancelSort: datagridParams && datagridParams.allowCancelSort == false ? false : true,

        virtualColumns : datagridParams && datagridParams.virtualColumns == false ? false : true,
        virtualScroll : datagridParams && datagridParams.virtualScroll == false ? false : true,

        showFilterRow: datagridParams && datagridParams.showFilterRow == true ? true : false,
        showSummaryRow: datagridParams && datagridParams.showSummaryRow == true ? true : false,
        showGroupSummary: datagridParams && datagridParams.showGroupSummary == true ? true : false,
        showColumnsMenu: datagridParams && datagridParams.showColumnsMenu == true ? true : false,

        onDrawSummaryCell: onDrawSummaryCell

    })
    /**
     * ========================================propertie================================================
     */

    /**
     * ======================================event==============================
     */
    grid.on('beforeload',function( param ){
        if(!param.url || param.url == null || param.url == ''){
            param.cancel = true;
        }
        param.params.page = param.params.pageIndex+1;
        if(datagridParams && datagridParams.beforeload){
            datagridParams.beforeload(param);
        }
    })
    grid.on('update',function(param){
        var el = $(grid.getEl()).find(".mini-pager-right");
        var pageSize = grid.getPageSize();
        var pageIndex = grid.getPageIndex();
        var t = grid.getTotalCount();
        var s = 0;
        var e = 0;
        if(t != 0){
            var s = pageIndex * pageSize+1;
            var e = t < pageSize ? t : (pageIndex + 1) * pageSize ;
        }
        var text = "显示 " + s + " 到 " + e + ",共 " + t + " 记录";
        el.text(text);
        if(datagridParams && datagridParams.update){
            datagridParams.update(param);
        }
    })
    grid.on('loaderror', function(e) {
        if(datagridParams && datagridParams.loaderror) {
            datagridParams.loaderror(e);
        }
        if(e.xhr.status == 606) {
            showInfoMsg('登录超时..', function() {
                window.location.href = e.xhr.getResponseHeader("Location");
            });
            return;
        }
    })
    grid.on('columnschanged',datagridParams && datagridParams.columnschanged ? datagridParams.columnschanged : null);
    grid.on('rowclick',datagridParams && datagridParams.rowclick ? datagridParams.rowclick : null);
    grid.on('rowdblclick',datagridParams && datagridParams.rowdblclick ? datagridParams.rowdblclick : null);
    grid.on('rowmousedown',datagridParams && datagridParams.rowmousedown ? datagridParams.rowmousedown : null);
    grid.on('cellclick',datagridParams && datagridParams.cellclick ? datagridParams.cellclick : null);
    grid.on('cellmousedown',datagridParams && datagridParams.cellmousedown ? datagridParams.cellmousedown : null);
    grid.on('headercellclick',datagridParams && datagridParams.headercellclick ? datagridParams.headercellclick : null);
    grid.on('headercellmousedown',datagridParams && datagridParams.headercellmousedown ? datagridParams.headercellmousedown : null);
    grid.on('headercellcontextmenu',datagridParams && datagridParams.headercellcontextmenu ? datagridParams.headercellcontextmenu : null);
    grid.on('preload',datagridParams && datagridParams.preload ? datagridParams.preload : function (data) {
        debugger;
        if(!data.result.success){
            showError(data.result);
        }
    });
    //grid.on('loaderror',datagridParams && datagridParams.loaderror ? datagridParams.loaderror : null);
    grid.on('load',datagridParams && datagridParams.load ? datagridParams.load :null);
    //grid.on('update',datagridParams && datagridParams.update ? datagridParams.update : null);
    grid.on('drawcell',datagridParams && datagridParams.drawcell ? datagridParams.drawcell : null);
    grid.on('cellbeginedit',datagridParams && datagridParams.cellbeginedit ? datagridParams.cellbeginedit : null);
    grid.on('cellcommitedit',datagridParams && datagridParams.cellcommitedit ? datagridParams.cellcommitedit : null);
    grid.on('cellendedit',datagridParams && datagridParams.cellendedit ? datagridParams.cellendedit : null);
    grid.on('celleditenter',datagridParams && datagridParams.celleditenter ? datagridParams.celleditenter : null);
    grid.on('selectionchanged',datagridParams && datagridParams.selectionchanged ? datagridParams.selectionchanged : null);
    grid.on('beforeselect',datagridParams && datagridParams.beforeselect ? datagridParams.beforeselect : null);
    grid.on('beforedeselect',datagridParams && datagridParams.beforedeselect ? datagridParams.beforedeselect : null);
    grid.on('select',datagridParams && datagridParams.select ? datagridParams.select : null);
    grid.on('deselect',datagridParams && datagridParams.deselect ? datagridParams.deselect : null);
    grid.on('cellvalidation',datagridParams && datagridParams.cellvalidation ? datagridParams.cellvalidation : null);
    grid.on('drawsummarycell',datagridParams && datagridParams.drawsummarycell ? datagridParams.drawsummarycell : null);
    grid.on('resize',datagridParams && datagridParams.resize ? datagridParams.resize : null);
    /**
     * ======================================event==============================
     */

    if(grid.getUrl() && grid.getUrl() != ''){
        grid.load( datagridParams && datagridParams.queryParams ? datagridParams.queryParams : {});
    }

    /**
     * ========================================stateful================================================
     */
    new ColumnStateful(grid, {      //扩展组件：列状态保持
        stateId: window.location.pathname+"_minigrid_"+id + (datagridParams && datagridParams.storageKey ? datagridParams.storageKey : '')
    });
    /**
     * ========================================stateful================================================
     */

    /**
     * ========================================copyable================================================
     */
    new CopyExcel(grid);
    /**
     * ========================================copyable================================================
     */

    function onDrawSummaryCell(e) {
        if(e.column.field == 'rowNumber'){
            e.cellHtml = "<div style='margin:5px; text-align:center'><b>合计:</b><div>"
        }
        //客户端汇总计算
        if (e.column.summaryType == "sum") {
            e.cellHtml = "<div style='margin:5px; text-align:center'><b>" + e.cellHtml+"</b><div>";
        }
    }
}


//初始化按键事件
function initKeyDown(target,KeyParams){
    debugger;
    $(".wayBillKeyDown").mouseover(function(){
        document.onkeyDownObj = $(this);
        if(document.onkeydown != keyDown){
            //按键事件
            document.onkeydown = keyDown;
        }
    });
    $(".wayBillKeyDown").mouseout(function(){
        document.onkeyDownObj = null;
    });
}

function keyDown(){
    var e = event || window.event || arguments.callee.caller.arguments[0];
    if(e && e.keyCode==27){ // 按 Esc
        //要做的事情
        console.log("27");
        $("#workflowTraceView").window("close");
    }
    if(e && (e.keyCode==113 || e.keyCode==120) && document.onkeyDownObj){ // 按 F2||F9
        //要做的事情
        console.log("F2");
        console.log(document.onkeyDownObj.text());
        document.onkeyDownObj.trigger("click");
    }
    if(e && e.keyCode==13){ // enter 键
        //要做的事情
        console.log("13");
    }
}
